import mapboxgl, { LngLatLike, Style, MapboxOptions } from 'mapbox-gl'
import { IMap } from '@/utils/map/index'
export interface IOpts extends MapboxOptions {}

export default class Mapbox implements IMap {
  private static instance: Mapbox | undefined
  private accessToken: string
  private container: string | HTMLElement
  private style: string | Style | undefined
  private center: LngLatLike | undefined
  private zoom: number
  private mapPromise: Promise<any>

  constructor(opts: IOpts) {
    const {
      accessToken = 'pk.eyJ1IjoicnVpd2FuZyIsImEiOiJjazJkZTY1OHIzY204M21tenF1NmV6bzZxIn0.zZUBhmaURzKhBg_bPJHOkA',
      container,
      style = 'mapbox://styles/mapbox/dark-v10',
      center = [0, 0],
      zoom = 2,
    } = opts
    this.accessToken = accessToken
    this.container = container
    this.style = style
    this.center = center
    this.zoom = zoom
    this.mapPromise = this.initMap()
  }

  destroy() {
    // const map = await this.mapPromise
    // map?.remove()
    Mapbox.instance = undefined
  }

  getRelMapPromise() {
    return this.mapPromise
  }

  private initMap() {
    const { container, style, zoom, center, accessToken } = this
    mapboxgl.accessToken = accessToken

    return new Promise((resolve) => {
      const map = new mapboxgl.Map({
        container, // container ID
        style, // style URL
        center, // starting position [lng, lat]
        zoom, // starting zoom
      })

      map.on('load', () => {
        resolve(map)
      })
    })
  }

  static getInstance(opts: MapboxOptions) {
    if (!this.instance) {
      this.instance = new Mapbox(opts)
    }
    return this.instance
  }
}
